#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版微信聊天记录导出工具
快速获取指定群聊的聊天记录
"""

import itchat
import json
from datetime import datetime
import os

def export_chat_history(chatroom_name, limit=500):
    """
    导出指定群聊的聊天记录
    
    Args:
        chatroom_name (str): 群聊名称
        limit (int): 获取消息数量限制
    """
    try:
        # 登录微信
        print("正在启动微信登录...")
        itchat.auto_login(hotReload=True)
        print("登录成功！")
        
        # 搜索群聊
        chatrooms = itchat.search_chatrooms(name=chatroom_name)
        
        if not chatrooms:
            print(f"未找到名为 '{chatroom_name}' 的群聊")
            return
        
        # 选择第一个匹配的群聊
        chatroom = chatrooms[0]
        print(f"找到群聊: {chatroom['NickName']}")
        
        # 获取聊天记录
        print("正在获取聊天记录...")
        messages = itchat.get_msg_list(toUserName=chatroom['UserName'], limit=limit)
        
        # 处理聊天记录
        chat_records = []
        for msg in messages:
            record = {
                'time': datetime.fromtimestamp(msg.get('CreateTime', 0)).strftime('%Y-%m-%d %H:%M:%S'),
                'sender': msg.get('ActualNickName', '未知'),
                'content': msg.get('Text', '[其他类型消息]'),
                'type': msg.get('Type', '未知')
            }
            chat_records.append(record)
        
        print(f"成功获取 {len(chat_records)} 条聊天记录")
        
        # 导出到文件
        filename = f"{chatroom_name}_聊天记录_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(chat_records, f, ensure_ascii=False, indent=2)
        
        print(f"聊天记录已导出到: {filename}")
        
        # 显示前几条记录预览
        print("\n前5条聊天记录预览:")
        for i, record in enumerate(chat_records[:5]):
            print(f"{i+1}. [{record['time']}] {record['sender']}: {record['content']}")
        
    except Exception as e:
        print(f"导出失败: {e}")
    finally:
        itchat.logout()
        print("已退出微信")

def main():
    """主函数"""
    print("简化版微信聊天记录导出工具")
    print("=" * 40)
    
    # 获取用户输入
    chatroom_name = input("请输入要导出的群聊名称: ").strip()
    
    if not chatroom_name:
        print("群聊名称不能为空")
        return
    
    limit_input = input("请输入要获取的消息数量 (默认500条): ").strip()
    limit = 500
    if limit_input:
        try:
            limit = int(limit_input)
        except ValueError:
            print("无效的数量，使用默认值500")
    
    # 开始导出
    export_chat_history(chatroom_name, limit)

if __name__ == "__main__":
    main() 